package com.dao.impl;

import com.dao.UserDao;
import com.entity.User;
import com.util.JDBCUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class UserDaoImpl implements UserDao {
    @Override
    public List<User> gerAllUser() {
        String sql="select * from user";
        List<Map<String,Object>>maps=JDBCUtil.queryListMap(sql);
        if (maps.size()>0) {
            ArrayList<User>users=new ArrayList<>();
            for (Map<String, Object> map : maps) {
                User user=new User((Integer)map.get("id"),(String)map.get("username"),(String)map.get("password"));
                users.add(user);
            }
            return users;
        }
        return null;
    }

    @Override
    public int insertUser(User user) {
        String sql="insert into user values(null,?,?)";
        int i=JDBCUtil.update(sql,user.getUsername(),user.getPassword());
        return i;
    }

    @Override
    public int delUserById(String id) {
        String sql="delete from user where id=?";
        int i=JDBCUtil.update(sql,id);
        return i;
    }

    @Override
    public int updateUser(User user) {
        String sql="update user set username=?,password=?where id=?";
        int i=JDBCUtil.update(sql,user.getUsername(),user.getPassword(),user.getId());
        return i;
    }

    @Override
    public User getOneUserById(String id) {
        String sql="select * from user where id=?";
        List<Map<String,Object>>maps=JDBCUtil.queryListMap(sql,id);
        if (maps.size()>0) {
            Map<String,Object>map=maps.get(0);
            User user=new User((Integer)map.get("id"),(String)map.get("username"),(String)map.get("password"));
            return user;
        }
        return null;
    }
}
